import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';

import { TreeService } from 'app/public/serve/tree/tree.service';
import { HintsService } from 'app/public/serve/hints/hints.service';

import { ipRule } from '../ip-rule.data';
import { ipRuleUrl } from '../ip-rule.url';

@Component({
  selector: 'ip-rule-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.css']
})

export class IpRuleTreeComponent implements OnInit {

  @Output() tree       = new EventEmitter<void>();
  @Output() nodeSelect = new EventEmitter<void>();

  treeData      : TreeNode[];
  selectedFile  : TreeNode[]; 

  constructor(
    private treeService: TreeService,
    private hintsService: HintsService    
  ) { }

  ngOnInit() {
    this._tree();
  }

  /**
   * 选中的节点
   * @param event 
   * @param id 
   */
  _nodeSelect(event, id) {

    if ((event.node.institutionName as string).indexOf("已禁用") > -1) {
      ipRule.isDisable = true;
    } else {
      ipRule.isDisable = false;
    }

    ipRule.tree.institutionName = event.node.institutionName;
    ipRule.tree.institutionId   = event.node.institutionId;
    ipRule.tree.parentId        = event.node.parentId;
    this.nodeSelect.emit();
  }

  /**
   * 树状图
   */ 
  _tree() {

    this.treeService
        .getParentInfos(ipRuleUrl.getParentInfos, 'institutionId', 'institutionName')
        .then((res: any) => {
          this.treeData = res;
          ipRule.tree.institutionName = this.treeData[0]['institutionName'];
          ipRule.tree.institutionId   = this.treeData[0]['institutionId'];
          ipRule.tree.parentId        = this.treeData[0]['parentId'];

          // 默认选中第一个节点（注释部分为：展开第一个节点）
          this.selectedFile = [this.treeData[0]];
          // this.treeData[0].expanded = true;
          // 展开所有节点
          this._expandAll();

          this.tree.emit();
          return
        })
        .catch((err: any) => {
          this.hintsService._operationHints('error', 'error');
          return
        });
  }

  /**
   * 展开所有树节点
   */
  private _expandAll() {
    this.treeData.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  // 递归
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

}
